var funcs = [];
var randomData = [];
var eventHandlers = [];

if (typeof (purl) == "undefined") {
    jQuery.getScript("http://ylfile.b0.upaiyun.com/Inspinia/Content/js/purl.js");
}

function WebUIJS() {}

var srcIsFunction = $.isFunction;
$.isFunction = function (obj) {
    if (typeof obj != "undefined" && obj != null && srcIsFunction(obj)) {
        return true;
    } else {
        return false;
    }
}


/**
 * 弹出一个消息页面 参考 http://jqweui.com/components#msg
 * @param {string} url 消息页面的url
 * @param {json} data 提交的数据,默认为null
 * @param {function(returnData)} onsuccess  当页面成功显示时回调
 * @param {function} onclose 当页面关闭时回调
 */
WebUIJS.ShowMsgPageByUrl = function (url, data, onsuccess, onclose) {
    __httpGetOrPostDataByHtml(url, data, 
        function (ret) {
            __showMsgPage(ret,function(ret){
                $(ret).closest(".weui-popup__container").data("autoremove",true);
                __callBackFuncOrStr(onsuccess,ret,[ret]);
            },onclose);
        }, 
        function (error) {
            WebUIJS.Toptip(error.message);
        });
}

/**
 * 关闭消息页面
 * @param {string,htmlelement} idOrEl 关闭指定的id的消息页,如果不传该参数,则关闭所有消息页
 */
WebUIJS.CloseMsgPage=function(idOrEl,autoRemove){
    
    var pageID="";

    if(typeof idOrEl == "string"){
        pageID=idOrEl;
    }
    else if(typeof idOrEl != "undefined")
    {
        pageID=$(idOrEl).closest(".weui-popup__container").attr("id");
    }
    
    __closeMsgPage(pageID);
}

/**
 * 打开一个弹出窗口
 * @param {any} url 数据连接
 * @param {any} data 数据
 * @param {function(modal)} onSuccessCallback 显示的时候回调
 * @param {any} onCloseCallback 关闭的时候回调
 * @param {any} httpMethod http调用的方式,get或post 二选一  默认为get
 */
WebUIJS.ModalByUrl = function (url, data, onSuccessCallback, onCloseCallback, httpMethod) {
    if (typeof httpMethod == "undefined") {
        httpMethod = "get";
    }

    function onSuccess(win) {

        WebUIJS.RefreshEvent(win);

        WebUIJS.CloseLoading();

        if (onSuccessCallback) {
            onSuccessCallback(win);
        }

        __raiseEvent("system.modalsuccess", $(win));
    }

    if (httpMethod == "get") {
        WebUIJS.Get(url,
            data,
            function (ret) {
                var tmp = $(ret);

                __showModal(tmp,
                    function (ret) {
                        try {
                            onSuccess(ret);
                        } catch (e) {
                            var p = 0;
                        }


                    },
                    onCloseCallback);
            },
            null,
            null,
            function () {
                WebUIJS.Loading();
            });
    } else {
        WebUIJS.Post(url,
            data,
            function (ret) {
                var tmp = $(ret);

                __showModal(tmp,
                    function (ret) {
                        try {
                            onSuccess(ret);
                        } catch (e) {
                            var p = 0;
                        }


                    },
                    onCloseCallback);

            },
            null,
            null,
            function () {
                WebUIJS.Loading();
            });
    }
}

/**
 * 打开一个弹出窗口,直接使用指定的元素,不经过网络获取
 * @param {htmlelement} element 要弹出窗体的元素
 * @param {function} onSuccessCallback 成功后回调
 * @param {function} onCloseCallback 关闭后,回调
 * @param {bool} noRefreshEvent 打开后是否刷新控件事件,默认为true
 */
WebUIJS.ModalByElement = function (element, onSuccessCallback, onCloseCallback, noRefreshEvent) {

    function onSuccess(win) {

        if (!noRefreshEvent) {
            WebUIJS.RefreshEvent(win);
        }

        if (onSuccessCallback) {
            onSuccessCallback(win);
        }

        __raiseEvent("system.modalsuccess", $(win));
    }

    __showModal($(element),
        function (ret) {
            try {
                onSuccess(ret);
            } catch (e) {
                var p = 0;
            }
        },
        onCloseCallback);
}


/**
 * 关闭指定的弹出窗口,如果不指定momdelindex参数,则关闭所有
 * @param {any} modalindex 弹出窗的id
 */
WebUIJS.CloseModalWindow = function (modalindex) {
    if (modalindex) {
        __closeModal(modalindex);
    } else {
        $(".weui-dialog").each(function () {
            __closeModal($(this).data("modalindex"));
        });

    }
}

WebUIJS.ModalByUrlWithResult = function (url, data, callback, httpMethod) {
    if (typeof httpMethod == "undefined") {
        httpMethod = "get";
    }

    var id = __getFuncID(callback);

    data.CallbackID = id;

    if (httpMethod == "get") {

    }

    WebUIJS.ModalByUrl(url,
        data,
        function (win) {
            callback(win);
        },
        httpMethod);

}

WebUIJS.ShowPopup = function (url, data, onSuccessCallback, onCloseCallback) {

    WebUIJS.Get(url,
        data,
        function (html) {
            var item = $($(html)[0]);

            $('body').append(item);

            item = $(item[0]);

            $(item).popup();

            $(item).data("onsuccesscallback", onSuccessCallback);
            $(item).data("onclosecallback", onCloseCallback);
            $(item).data("url", url);
            $(item).data("requestdata", data);

            WebUIJS.RefreshEvent(item);

            if (onSuccessCallback) {
                onSuccessCallback(item);
            }
            
            
        },
        null,
        function () {
            WebUIJS.CloseLoading();
        },
        function () {
            WebUIJS.Loading();
        }
    );
}

WebUIJS.ClosePopup = function (sender,remove=false) {
    var onCloseCallback;

    if (sender) {
        onCloseCallback = $(sender).data("onclosecallback");
    }

    $.closePopup(sender, remove);

    if (onCloseCallback) {
        __callBackFuncOrStr(onCloseCallback, sender);
    }

}

WebUIJS.ShowDataPicker = function (url, data, onSelectedCallback, onSuccessCallback, onCloseCallback) {
    
    WebUIJS.Get(url,
        data,
        function (html) {
            var item = $($(html)[0]);

            $('body').append(item);
            
            item = $(item[0]);

            $(item).popup();

            $(item).data("url", url);
            $(item).data("requestdata", data);
            $(item).data("onsuccesscallback", onSuccessCallback);
            $(item).data("onselectedcallback", onSelectedCallback);

            $(item).data("onclosecallback", onCloseCallback);

            WebUIJS.RefreshEvent(item);

            var pageIndex = 1;

            var listContent = $(item).find(".modal-content");

            listContent.data("loadmorecallback",
                function (e) {
                    pageIndex += 1;
                    data[$(item).data("pageindexkey")] = pageIndex;
                    WebUIJS.Get(url,
                        data,
                        function(moreDataHtml) {
                            var children = $(moreDataHtml).find(".modal-content").children();

                            $(children).each(function() {
                                listContent.append($(this));

                                WebUIJS.RefreshEvent($(this));
                            });

                            e.LoadComplete();
                        });
                });

        },
        null,
        function () {
            WebUIJS.CloseLoading();
        },
        function() {
            WebUIJS.Loading();
        }
        );
}

WebUIJS.CloseDataPicker = function (sender) {

    var onCloseCallback;

    if (sender) {
        onCloseCallback = $(sender).data("onclosecallback");
    }

    $.closePopup(sender);

    if (onCloseCallback) {
        __callBackFuncOrStr(onCloseCallback, sender);
    }
}

WebUIJS.ShowLogin = function (url, title, text, onSuccessCallback, onCancelCallback) {
    $.login({
        title: title,
        text: text,
        username: '', // 默认用户名
        password: '', // 默认密码
        onOK: function (username, password) {

            onSuccessCallback(username, password);
        },
        onCancel: function () {
            onCancelCallback();
        }
    });
}


WebUIJS.ShowNotification = function (title, text, onClick, onClose, timeout) {
    if (typeof timeout == "undefined") {
        timeout = 4000;
    }

    $.notification({
        title: title,
        text: text,
        media: "", // "<img src='...'>",
        data: null,
        onClick: onClick,
        onClose: onClose,
        time: timeout
    });

}

WebUIJS.CloseNotification = function () {
    $.closeNotification();
}

WebUIJS.Loading = function (timeout) {
    $.showLoading();

    if (timeout && timeout > 0) {
        setTimeout(function () {
                WebUIJS.CloseLoading();
            },
            timeout);
    }
}

WebUIJS.CloseLoading = function () {
    $(".weui_loading_toast").remove();
    $.hideLoading();
}


WebUIJS.Alert = function (text, onhideCallback) {
    $.alert(text,
        function () {
            //$('body').css("overflow", "auto");
            __callBackFuncOrStr(onhideCallback, this);
        });

    //$('body').css("overflow", "hidden");
}

/**
 * 显示一个居中的提示层
 * @param {} text 显示的文本
 * @param {} type 显示的类型:  success,cancel 二选一
 * @param {} timeout  超时隐藏时间,默认2秒
 * @param {} onHideCallback 隐藏时,回调函数
 * @returns {} 
 */
WebUIJS.Toast = function (text, type, timeout, onHideCallback) {
    if (typeof timeout == "undefined") {
        timeout = 2000;
    }

    $.toast(text,
        type,
        function () {
            if (typeof onHideCallback != "undefined") {
                __callBackFuncOrStr(onHideCallback);
            }

        });
}

/**
 * 显示在页面顶部的轻量级提示，一般用来反馈用户的操作结果，比如表单校验失败等。
 * @param {any} text 提示的文本内容
 * @param {any} duration 显示的时间
 * @param {any} type 类型:success,error,warning 三选一,默认为success
 */
WebUIJS.Toptip = function (text, duration=1000, type="success") {
    $.toptip(text, duration, type);
}

WebUIJS.Toptip.Style={
    Success:"success",
    Warning:"warning",
    Error:"error"
}

/**
 * 从下方弹出一个按钮列表,
 * @param {array} actions 按钮的配置 [{text:"",className:"",onClick:""}]
 * @param {any} title 操作栏的标题,默认为 操作
 * @param {any} onCloseCallback 关闭时的回调
 */
WebUIJS.ShowActions = function (actions, title, onCloseCallback) {
    $.actions({
        actions: actions,
        title: title,
        onClose: onCloseCallback
    });
}

/**
 * 显示图片大图
 * @param {string} imgUrl 图片地址
 * @param {array} btnconfig 图片按钮配置 格式为:{title:"",iconclass:"",onclick:function(e){}}}
 */
WebUIJS.ShowImage = function (imgUrl, btnconfig) {
    var btnStr = "";

    if (btnconfig && btnconfig.length > 0) {
        btnStr = '<div class="weui-gallery__opr">';

        for (var i = 0; i < btnconfig.length; i++) {
            var btn = btnconfig[i];
            btnStr += '<a>';

            btnStr += '<i class="' + btn["iconclass"] + '"></i>';

            btnStr += '</a>';

        }

        btnStr += '</div>';
    }

    var str = '<div class="weui-gallery" style="display: block">' +
        '<span class="weui-gallery__img" style="background-image: url(\'' +
        imgUrl +
        '\');"></span>' +
        btnStr +
        //'<div class="weui-gallery__opr">' +
        //    '<a href="javascript:" class="weui-gallery__del">' +
        //        '<i class="weui-icon-delete weui-icon_gallery-delete"></i>' +
        //    '</a>' +
        //'</div>' +
        '</div>';

    var mask=$(str);

    var div = $('body').append(mask);

    if (btnconfig && btnconfig.length > 0) {
        var opts = $(div).find(".weui-gallery__opr");

        for (var j = 0; j < btnconfig.length; j++) {
            var btn = btnconfig[j];

            if (!(typeof btn.onclick == 'undefined' && btn.onclick == null)) {
                $(opts[j]).click(function(e){
                    btn.onclick(e)
                    e.stopPropagation();
                } );
            }
        }
    }

    div.find(".weui-gallery").click(function () {
        $(mask).hide();
        $(mask).remove();
    });
}

/**
 * 用于提交指定的表单
 * @param {html元素} el 如果传入的元素是form,则直接提交,如果不是,则查找最近的一个form,然后提交
 */
WebUIJS.Submit = function (el, onSuccessCallback) {

    var targetEl = el;

    el = $(el);

    if (!el.is("form,div[data-innerform=\"True\"],.weui-dialog")) {
        el = $(el).closest(".weui-dialog");

        if (el==null || el.length<=0) {
            el = $(el).closest("form,div[data-innerform=\"True\"]");
        }
    }

    if (el.length <= 0) {
        console.log("控件未包含在任何form内");
        return;
    }

    if (el.is("form")) {
        __formSubmit(el, onSuccessCallback);
    } else if (el.is("div[data-innerform=\"True\"]")) {
        __divFormSubmit(el, onSuccessCallback);
    } else if (el.is(".weui-dialog")) {

        var modal = $(el).find("div[data-innerform=\"True\"],form:not(.fakeform)");

        if (modal.length > 0) {
            var form = $(modal); // $(modal).find("div[data-innerform=\"True\"],form");

            var modalID = $(el).data("modalindex");
            var onclose = $(el).data("onclose");

            if (form.is("div")) {
                __divFormSubmit(form,
                    function (ret) {
                        //__showModal(ret, null, onclose, true);
                        //__closeModal(modalID, false);

                        if (onSuccessCallback) {
                            onSuccessCallback(targetEl);
                        }
                    }, {
                        modalindex: modalID
                    });
            } else {
                __formSubmit(form,
                    function (ret) {
                        //__showModal(ret, null, onclose, true);
                        //__closeModal(modalID, false);
                        if (onSuccessCallback) {
                            onSuccessCallback(targetEl);
                        }
                    }, {
                        modalindex: modalID
                    });
            }
        }
    }
}

// WebUIJS.ScrollSpy=function(container,el,triggerCallback){
//     var ss=container.scrollHeight() - ($(window).height() + $(".instest").scrollTop());

//     $(container).infinite(ss).on("infinite",function(){
//         if(triggerCallback){
//             __callBackFuncOrStr(triggerCallback,container,[]);
//         }
//     })
// }

// WebUIJS.DestroyScrollSpy=function(container){
//     $(container).destroyInfinite();
// }

/**
 * 跳转到指定url
 * @param {string} url  跳转的Url
 * @param {} sender 触发该调转的元素,跳转时,会锁定该元素,无法重复触发
 * @returns {} 
 */
WebUIJS.GoTo = function (url, sender) {
    
    if (typeof sender != 'undefined' && sender != null) {
        if ($(sender).data("going")) {
            return;
        }

        var closestEl = $(sender).closest(".weui-dialog,.weui-popup__container");

        if (closestEl.is('.weui-dialog')) {

            var modalID = $(closestEl).data("modalindex");

            WebUIJS.ModalByUrl(url,
                null,
                function (item) {
                    $(sender).removeAttr("data-going");//.data("going", null);
                    __closeModal(modalID);
                });
        }
        else if (closestEl.is(".weui-popup__container")) {
            var onsuccesscallback = $(sender).data("onsuccesscallback");
            var onclosecallback = $(sender).data("onclosecallback");
            var url = $(sender).data("url");
            var requestdata = $(sender).data("requestdata");
            
            WebUIJS.ShowPopup(url,
                requestdata,
                function (e) {
                    $(sender).removeAttr("data-going");

                    $.closePopup(sender, true);

                    //WebUIJS.ClosePopup(sender,true);

                    if (onsuccesscallback) {
                        __callBackFuncOrStr(onsuccesscallback, e);
                    }
                },
                onclosecallback);
        }
        else {
            window.location.href = url;
        }
    } else {
        window.location.href = url;
    }


}

/**
 * 刷新当前页面
 * @param {} sender 
 * @returns {} 
 */
WebUIJS.Refresh = function (sender) {

    if (!sender) {
        sender = null;
    }

    WebUIJS.GoTo(window.location.href, sender);
}

var isPickerOpened = false;

WebUIJS.RefreshEvent = function (collection) {

    var swiped = function (e) {
        $(e).find(".weui-cell_swiper").each(function () {
            var autoplayDelay = parseInt($(this).data("autoplay"));

            var config = {
                autoplay: autoplayDelay,
                loop: true,
                pagination: ".swiper-pagination",
                //{
                //    el: '.swiper-pagination',
                //    dynamicBullets: true,
                //    dynamicMainBullets: 1
                //},
                autoHeight: true
            }

            try {
                $(this).swiper(config);
            } catch (e) {

            }
        });
        //$(e).find(".weui-cell_swiped").swipeout();
    }

    var pullToRefresh = function (e) {
        $(e).find(".pullToRefreshCollection").each(function () {
            var that = $(this);
            var url = $(that).data("refreshurl");

            if(that.find(".weui-pull-to-refresh__layer").length<=0){
                that.prepend(
                    "<div class=\"weui-pull-to-refresh__layer\"><div class=\'weui-pull-to-refresh__arrow\'></div><div class=\'weui-pull-to-refresh__preloader\'></div><div class=\"down\">下拉刷新</div><div class=\"up\">释放刷新</div><div class=\"refresh\">正在刷新</div></div>")
    
            }

            
            var callback = that.data("onpulltorefresh");
            

            //callback="__callBackFuncOrStr(\"" + callback + "\",this,[e])";

            var ea={
                target:that,
                LoadComplete:function(canLoadMore){
                    $(that).pullToRefreshDone();
                }
            }


            $(that).pullToRefresh().on("pull-to-refresh",
                function(done) {

                    if (url && url !== "") {
                        WebUIJS.Get(url,
                            null,
                            function(data) {
                                if (data) {
                                    $(that).data("pageindex",1);

                                    $(that).find(".weui-panel__bd").first().empty();

                                    $(data).find("div.weui-panel__bd").first().children()
                                        .appendTo($(that).find(".weui-panel__bd").first());
                                    
                                    $(that).find(".weui-panel__bd").children().each(function () {
                                        WebUIJS.RefreshEvent($(this));
                                    });

                                    ea.LoadComplete();

                                    __callBackFuncOrStr(callback, that, [ea]);
                                }
                            });
                    } else {
                        __callBackFuncOrStr(callback, that, [ea]);
                    }
                    

                });
        });
    }

    var loadmore = function (e) {
        var str =
            "<div class=\"weui-loadmore\"><i class=\"weui-loading\"></i><span class=\"weui-loadmore__tips\">正在加载</span></div>";

        $(e).find("[data-loadmore=\"True\"]").each(function (e) {
            var that = $(this);
            var loading = false;
            var url = $(that).data("loadmoreurl");
            //var pageindex = parseIntEx($(that).data("currentpageindex"), 1);
            var pageindexkey = $(that).data("pageindexkey");

            if (!pageindexkey) {
                pageindexkey = "pageindex";
            }

            var holder=$(that).find(".holder");
            
            if($(that).find(".weui-loadmore").length<=0){
                if(holder.length<=0){
                    $(that).append(str);
                }
                else{
                    $(holder).before(str);
                }
            }

            var loadmore=$(that).find(".weui-loadmore");

            //holder.height($(that).closest(".weui-tabbar-container").find(".weui-tabbar").height());  

            var loadMoreCallback = $(that).data("loadmorecallback");
        
            var obj = $(that).infinite();

            //$(that).data("infinite", obj);

            var ea={
                target:that,
                LoadComplete:function(canLoadMore){
                    loading=false;

                    if(typeof canLoadMore=="bool" && canLoadMore==false){
                        obj.destroyInfinite();
                        loadmore.remove();
                    }
                }
            }

            obj.on("infinite",
                function () {
                    if (loading) return;
                    loading = true;
                    
                    if (url && url !== "") {
                        var pageIndex = parseIntEx($(that).data("pageindex"), 1);
                        
                        WebUIJS.Get(url.replace("{" + pageindexkey + "}", ++pageIndex),
                            null,
                            function(data) {
                                if (data) {
                                    $(that).data("pageindex", pageIndex + 1);

                                    $(data).find("div.weui-panel__bd").first().children()
                                        .appendTo($(that).find(".weui-panel__bd").first());

                                    $(that).find(".weui-panel__bd").children().each(function() {
                                        WebUIJS.RefreshEvent($(this));
                                    });

                                    ea.LoadComplete();

                                    __callBackFuncOrStr(loadMoreCallback, that, [ea]);
                                }
                            });
                    } else {
                        __callBackFuncOrStr(loadMoreCallback, that, [ea]);
                    }
                    

                    //loading = false;
                });

        });

    }

    //多图片文件上传
    var multiImageUploader = function (e) {
        $(e).find('.weui-cells_multiimageuploader').each(function () {
            var that = $(this);
            var name = $(that).data("name");
            var ajaxupload = false;// $(that).data("ajaxposturl"); //是否异步上传
            var ajaxurl = $(that).data("ajaxposturl"); //异步上传地址

            if (ajaxurl !== "") {
                ajaxupload = true;
            } else {
                ajaxupload = false;
            }

            $(that).find(".weui-uploader__input-box").click(function () {
                var newli = $( "<li class=\"weui-uploader__file\"><div class=\"weui-uploader__file-content\">等待上传</div><img  /></li>").appendTo(ul);

                var file = addFile(newli);

                file.click();

                liClick(newli);

                
                //ul.append(newli);
            });

            var liClick=function(lisource){
                $(lisource).find("weui-uploader__file-content").click(function(e){
                    e.stopPropagation();
                })

                $(lisource).click(function () {
                    WebUIJS.ShowActions([{
                            text: "查看",
                            className: "color-primary",
                            onClick: function () {
                                var url=$(lisource).find("input[type=\"hidden\"]").val();

                                if(url && url!=""){
                                    WebUIJS.ShowImage(url);
                                }

                                $.closeActions();
                            }
                        },
                        {
                            text: "替换",
                            className: "color-warning",
                            onClick: function () {
                                var file = (lisource).find(":file");

                                if (file.length > 0) {
                                    file.click();
                                } else {
                                    file = addFile(lisource);

                                    file.click();
                                }
                                $.closeActions();
                            }
                        },
                        {
                            text: "删除",
                            className: "color-danger",
                            onClick: function () {
                                $(lisource).remove();
                                $.closeActions();
                            }
                        }
                    ]);


                });
            }

            var addFile = function (parent) {
                var file=$("<input type=\"file\" accept=\"image/*\" capture=\"camera\"/>");

                if(ajaxupload){
                    file.data("name",name)
                }
                else{
                    file.attr("name",name);
                }

                $(parent).append(file);

                var uploadStatus=parent.find(".weui-uploader__file-content");

                __fileChangeHandler(file[0],
                    ajaxupload,
                    ajaxurl,
                    function (e1) {
                        uploadStatus.text(e1.toFixed(0) + "%");
                    },
                    function (data) {
                        if (ajaxupload) {
                            WebUIJS.Toptip("上传成功",1000,"success");

                            $(parent).append("<input type=\"hidden\" name=\"" +
                                name +
                                "\" value=\"" +
                                data.ReturnData.ImageUrl +
                                "\" />");

                            $(parent).find(":file").empty();
                        }

                        $(parent).find("img").attr("src",data.ReturnData.ImageUrl)

                        $(parent).removeClass("weui-uploader__file_status");
                    },
                    function (e) {
                        WebUIJS.Toptip("上传错误:" + e.Message,1000,"error");
                        $(parent).remove(); 
                    },function(){
                        $(parent).addClass("weui-uploader__file_status");
                    });

                return file;
            }



            var ul = $(that).find(".weui-uploader__files");

            $(ul).find("li").each(function () {
                var li = $(this);

                liClick(li);
            });
        });
    }

    var singleImageUploader = function (e) {
        $(e).find('.weui-cells_singleimage').each(function () {
            var enableUpload = $(this).data("enableupload") == "True";
            var uploadScript = $(this).data("uploadscript");
            var that = $(this);
            var postUrl = $(that).data("ajaxposturl");
            var file = $(that).find(":file");

            var isAjax = postUrl != "";

            if (isAjax) {
                var name=$(file).attr("name");
                $(file).data("name",name);
                $(file).removeAttr("name");
            }

            __fileChangeHandler(file[0],
                isAjax,
                postUrl,
                function(e){
                    //if(e % 10 ==0)
                        //WebUIJS.Toptip("已上传:" + e.toFixed(0) + "%",1000);
                },
                function (data) {
                    if(data.IsSuccess){
                        WebUIJS.Toptip("上传成功",WebUIJS.Toptip.Style.Success);
                        $(that).find('img').attr("src", data.ReturnData.ImageUrl);
                        $(that).find(":hidden").attr("value", data.ReturnData.ImageUrl);
                        file.empty();
                    }
                    else{
                        WebUIJS.Toptip("上传失败:" + data.Message,WebUIJS.Toptip.Style.Warning);
                    }
                })

            $(this).click(function () {
                var config = [{
                    text: '查看',
                    className: "color-primary",
                    onClick: function () {
                        var url=$(that).find("input[type=\"hidden\"]").val();

                        if(url && url!=""){
                            WebUIJS.ShowImage(url);
                        }

                        $.closeActions();
                        //WebUIJS.ShowImage(that.find("img").attr("src"));
                    }
                }];

                if (enableUpload) {
                    if (uploadScript && uploadScript!="") {
                        config.push({
                            text: "替换",
                            className: "color-warning",
                            onClick: function () {
                                __callBackFuncOrStr(uploadScript, that);
                                $.closeActions();
                            }
                        });
                    } else {
                        
                        config.push({
                            text: "替换",
                            className: "color-warning",
                            onClick: function (e) {
                                //e.stopPropagation();
                                
                                $(that).find(":file").click();
                                $.closeActions();
                            }
                        });
                    }
                }

                config.push({
                    text: "删除",
                    className: "color-danger",
                    onClick: function () {
                        $(that).find(":file").empty();
                        $(that).find("img").attr("src", null);
                        $(that).find(":hidden").attr("value", null);
                    }
                });

                $.actions({actions:config});
            });
        });
    }

    var mobileVCode = function (e) {
        $(e).find(".weui-cell_mobilevcode .weui-vcode-btn").click(function () {
            var that = $(this);

            if (that.is("[disabled]")) {
                WebUIJS.Alert("请等待接收");
                return false;
            }

            var cell = $(this).closest(".weui-cell");

            var forSelector = $(cell).data("for");
            var paramname = $(cell).data("paramname");
            var script = $(cell).data("buttonscript");
            var disableSec = $(cell).data("disablesec");

            if (disableSec == "") {
                disableSec = 30;
            } else {
                disableSec = parseInt(disableSec);
            }

            var maxDisableSec = disableSec;
            var currentSec = 0;

            if (!isEmpty(script)) {
                __callBackFuncOrStr(script, cell);
            } else {
                var url = $(that).data("smsurl");

                if (url == "") {
                    return;
                }

                var args = {};
                var value = "";
                if (forSelector != "") {
                    value = $(forSelector).val();
                } else {
                    value = cell.find(":text").val();
                }

                if (isEmpty(value)) {
                    WebUIJS.Toptip("请输入手机号码", 2, "error");
                    return false;
                }

                args[paramname] = value;

                WebUIJS.GetJson(url,
                    args,
                    function (data) {
                        if (data.IsSuccess) {


                            var timerID;

                            timerID = setInterval(function () {
                                    $(that).text("剩余" + (maxDisableSec - currentSec) + "秒");

                                    if (currentSec >= maxDisableSec) {
                                        clearInterval(timerID);
                                        $(that).removeAttr("disabled");
                                        $(that).text("获取验证码");
                                    } else {
                                        currentSec++;
                                    }
                                },
                                1000);

                            WebUIJS.Toptip("发送成功到" + value +",请查收", 2000);


                        } else {
                            WebUIJS.Toptip(data.Message, 2000, "error");
                            $(that).removeAttr("disabled");
                        }
                    },
                    function (e) {
                        WebUIJS.Toptip("调用服务失败", 2000, "error");
                        $(that).removeAttr("disabled");
                    },
                    null,
                    function (e) {
                        $(that).attr("disabled", "disabled");
                    });

            }


        });


    }

    var vcode = function (e) {
        $(e).find(".weui-cell_vcode .weui-vcode-img").click(function () {
            var that = $(this);

            var url = $(that).attr("src");

            $(that).attr("src", null);

            $(that).attr("src", url);
        });
    }

    //form字段中,出现错误的时候,点击红色感叹号按钮在顶部显示提示框
    var warnTips = function (e) {
        $(e).find(".weui-icon-warn,.weui-cells_radio_title.weui-cell_warn,.weui-cells_checkbox_title.weui-cell_warn")
            .each(function () {
                $(this).click(function () {
                    var btn = $(this);

                    if ($(this).is(".weui-cells__title")) {
                        btn = $(this).find("i");
                    }

                    var error = $(btn).data("error");

                    WebUIJS.Toptip(error, 2000, "error");
                });
            });

    }

    var datepicker = function (e) {
        $(e).find(".datepicker").each(function () {
            var that = $(this);
            var textbox = $(that).find(":text");

            var onchangescript = $(that).data("onchange");

            var value = textbox.val();

            var opt = {
                onChange: function (p, values, displayValues) {
                    if (typeof onchangescript != "undefined") {
                        __callBackFuncOrStr(onchangescript, textbox);
                    }
                },
                dateFormat: "yyyy-mm-dd",
                values: [value]
            };

            var max = textbox.data("max");
            var min = textbox.data("min");

            if (max != "" || max != null) {
                opt.maxDate = max;
            }

            if (min != "" || min != null) {
                opt.minDate = min;
            }

            $(textbox).calendar(opt);
        });
    }

    var dateptimeicker = function (e) {
        $(e).find(".datetimepicker").each(function () {
            var that = $(this);
            var textbox = $(that).find(":text");

            var onchangescript = $(that).data("onchange");

            var value = textbox.val();

            var opt = {
                onChange: function (picker, values, displayValues) {
                    if (typeof onchangescript != "undefined") {
                        __callBackFuncOrStr(onchangescript, textbox);
                    }
                },
                dateFormat: "yyyy-MM-dd",
                values: [value]
            };

            var max = textbox.data("max");
            var min = textbox.data("min");

            if (max != "" || max != null) {
                opt.max = max;
            }

            if (min != "" || min != null) {
                opt.min = min;
            }

            $(textbox).datetimePicker(opt);
        });
    }

    var timerPicker = function (e) {
        $(e).find(".timepicker").each(function () {
            var that = $(this);
            var textbox = $(that).find(":text");

            var onchangescript = $(that).data("onchange");

            var parse = function (str) {
                // 把字符串转换成数组，用来解析初始值
                // 如果你的定制的初始值格式无法被这个默认函数解析，请自定义这个函数。比如你的时间是 '子时' 那么默认情况这个'时'会被当做分隔符而导致错误，所以你需要自己定义parse函数
                // 默认兼容的分隔符
                var t = str.split(/:|时|分|秒/);
                return t[0].split(/\D/).concat(t[1].split(/:|时|分|秒/)).filter(function (d) {
                    return !!d;
                });
            }


            var max = textbox.data("max");
            var min = textbox.data("min");

            if (max == "" || max == null) {
                max = 23;
            } else {
                max = parseInt(max);
            }

            if (min == "" || min == null) {
                min = 0;
            } else {
                min = parseInt(min);
            }

            var formatNumber = function (n) {
                return n < 10 ? "0" + n : n;
            }

            var hours = [];
            for (var i = min; i < max; i++) hours.push(formatNumber(i));

            var minutes = [];
            for (var i = 0; i < 60; i++) minutes.push(formatNumber(i));

            $(textbox).picker({
                title: "请选择",
                cols: [{
                        textAlign: 'center',
                        values: hours
                    },
                    {
                        textAlign: 'center',
                        values: minutes
                    }
                ],
                value: parse($(textbox).val()),
                onChange: function (picker, values) {
                    $(textbox).val(values[0] + ":" + values[1]);

                    if (typeof onchangescript != "undefined") {
                        __callBackFuncOrStr(onchangescript, textbox);
                    }
                }
            });


        });
    }

    var counter = function (e) {
        $(e).find(".weui-cell_counter").each(function () {

            var textbox = $(this).find(":text");

            var max = textbox.data("max");
            var min = textbox.data("min");

            if (max != "" || max != null) {
                max = parseInt(max);
            } else {
                max = null;
            }

            if (min != "" || min != null) {
                min = parseInt(min);
            } else {
                min = null;
            }

            $(this).find('.weui-count__decrease').click(function (e) {
                var $input = $(e.currentTarget).parent().find('.weui-count__number');
                var number = parseInt($input.val() || "0") - 1
                if (min != null && number < min) number = min;
                $input.val(number);
            });

            $(this).find('.weui-count__increase').click(function (e) {
                var $input = $(e.currentTarget).parent().find('.weui-count__number');
                var number = parseInt($input.val() || "0") + 1
                if (max != null && number > max) number = max;
                $input.val(number);
            });
        });
    }

    var slider = function (e) {
        try {
            $(e).find(".weui-cells_slider-box").slider(function (percent) {
                var max = parseInt($(this).data("max"));
                var min = parseInt($(this).data("min"));

                $(this).find("input").val((percent / 100) * max);
            });
        } catch (e) {

        } 
        
    }

    var querybox = function (e) {

        //初始化查询框的radio

        $(e).find(".weui-querybox :checkbox,:radio").change(function () {
            if ($(this).is(":checked")) {
                $(this).closest(".weui-querybox-item").addClass("weui-querybox-item-checked");
            } else {
                $(this).closest(".weui-querybox-item").removeClass("weui-querybox-item-checked");
            }

            if ($(this).closest(".weui-querybox-item").data("onchangesubmit") == "true") {
                WebUIJS.Submit($(this).closest(".weui-querybox").find("form"));

                //$(this).closest(".weui-querybox").find("form").submit();
            }
        });

        $(e).find(".weui-querybox .weui-querybox-radio .weui-querybox-item").each(function () {
            var item = $(this);
            var radio = $(item).find(":radio");

            $(this).click(function () {
                if (radio.is(":checked")) {
                    var name = $(radio).attr("name");

                    if ($(':radio[name="' + name + '"]:checked')[0] == radio[0]) {
                        return;
                    }

                    radio.prop("checked", null);
                } else {
                    radio.prop("checked", "checked");
                }

                __triggerRadioGroupChange(radio);
            });
        });

        $(e).find(".weui-querybox .weui-querybox-check .weui-querybox-item").each(function () {
            var item = $(this);
            var checkbox = $(item).find(":checkbox");

            $(this).click(function () {
                if (checkbox.is(":checked")) {
                    checkbox.prop("checked", null);
                } else {
                    checkbox.prop("checked", "checked");
                }

                checkbox.trigger("change");
            });
        });

        $(e).find(".weui-querybox").find(".weui-querybox-radio,.weui-querybox-check").each(function () {
            var that = $(this);

            var displayQty = $(that).data("display");

            if (typeof displayQty != "undefined" && displayQty != "") {
                var qty = parseInt(displayQty);

                if (qty > 0) {
                    $(that).find("span.btnShowAll").click(function () {

                        if ($(this).data("showall") == true) {
                            $(that).find(".weui-querybox-block").slice(qty).hide();
                            $(this).data("showall", false);
                            $(this).html("全部  &and;");
                        } else {
                            $(that).find(".weui-querybox-block").show();
                            $(this).data("showall", true);
                            $(this).html("全部 &or;");
                        }
                    });

                    that.find(".weui-querybox-block").slice(qty).hide();
                    that.find("span.btnShowAll").data("showall", false);
                }
            }
        });

        $(e).find(".weui-querybox .weui-querybox-radio .weui-querybox-item").first().click();

        $(e).find(".weui-querybox-search-bar").click(function () {
            var barID = $(this).attr("for");

            $("#" + barID).slideDown(300);
        });

        $(e).find(".weui-querybox .close-querybox-button").click(function () {
            $(this).closest('.weui-querybox').slideUp(300);
        });

        $(e).find(".weui-querybox :submit").click(function () {
            WebUIJS.Submit($(this).closest(".weui-querybox").find("form"));
        });

        $(e).find(".weui-querybox").click(function (e) {
            if (e.target == this) {
                $(this).slideUp(300);
            }
        });


    }

    var listbar = function (e) {
        $(e).find(".listbar").click(function () {
            $(this).find(".listbar-item-selector-option").removeClass("listbar-item-selector-option-visible");
        });

        $(e).find(".listbar").each(function () {
            var option = $(this).find(".listbar-item-selector-option");

            $(body).click(function () {
                option.removeClass("listbar-item-selector-option-visible");
            });

        });

        $("body").click(function () {
            $(".listbar-item-selector-option").removeClass("listbar-item-selector-option-visible");
        });


        $(e).find(".listbar").find(".listbar-item-selector-btn").each(function () {
            var item = $(this).closest(".weui-flex__item");
            var that = $(this);


            var option = $(item).find(".listbar-item-selector-option");

            $(this).click(function (e1) {
                e1.stopPropagation();
                $(option).toggleClass("listbar-item-selector-option-visible");

                if ($(option).is(".listbar-item-selector-option-visible")) {
                    $(that).find(".direction").html(" &and;");
                } else {
                    $(that).find(".direction").html(" &or;");
                }


            });

            $(item).click(function (e1) {
                e1.stopPropagation();
                if ($(e.target).is(".listbar-item-selector-option")) {
                    $(option).removeClass("listbar-item-selector-option-visible");
                }
            });

            var autoClose = $(item).data("autoclose");
            var autosubmit = $(item).data("autosubmit");

            if (autoClose == true) {
                $(item).find("label.weui-check__label").click(function (e) {
                    e.stopPropagation();
                    setTimeout(function () {
                            $(option).removeClass("listbar-item-selector-option-visible");
                        },
                        100);

                });
            }

            if (autosubmit == true) {
                $(item).find(":radio,:checkbox").change(function () {
                    //TODO:提交表单
                    WebUIJS.Submit(this);
                });
            }
        });

        $(e).find(".listbar").find(".listbar-item-switch-btn").each(function () {
            var btn = $(this);

            var input = $(btn).find(":radio,:checkbox");

            $(btn).click(function () {
                //e.stopPropagation(); 
                __switchElementChecked(input);
            });

            var autosubmit = that.data("autosubmit") == "True";

            $(input).change(function () {
                if (input.is(":checked")) {
                    btn.addClass("listbar-item-switch-btn-checked");
                } else {
                    btn.removeClass("listbar-item-switch-btn-checked");
                }

                if (autosubmit) {
                    WebUIJS.Submit(btn);
                }
            });
        });
    };

    var listview = function (e) {
        $(e).find(".weui-listview").each(function () {
            var listview = $(this);

            if ($(this).find(".weui-pull-to-refresh__layer").length>0) 
            {
                var callonrefresh = listview.data("callonrefresh");

                listview.pullToRefresh(function () {
                    __callBackFuncOrStr(callonrefresh, listview);
                    //listview.pullToRefreshDone();
                });
            }

            var callOnMore = listview.data("callonloadmore");

            if (typeof callOnMore != "undefined") {
                $(document.body).infinite().on("infinite",
                    function () {
                        __callBackFuncOrStr(callOnMore, listview);
                    });
            }
        });

    }


    if ($(collection).find(".weui-cells_city-picker").length>0) {
        if (!$("input").cityPicker) {
            $.getScript("https://cdn.bootcss.com/jquery-weui/1.2.0/js/city-picker.js", function () {
                cityPicker(collection);
            });
        }
    }

    if ($(".weui-cells_city-picker").length>0) {
        if (!$("input").cityPicker) {
            WebUIJS.Loading();

            $.getScript("https://cdn.bootcss.com/jquery-weui/1.2.0/js/city-picker.js", function () {
                WebUIJS.CloseLoading();
                cityPicker(collection);
            });
        }
    }

    

    var cityPicker = function (e) {
        $(e).find(".weui-cells_city-picker").each(function () {
            
            var that = $(this);
            var text = $(that).find(":text");

            var disableDistrict = that.data("disabledistrict") == "True";
            var pickertitle = that.data("pickertitle");

            

            var p=text.cityPicker({
                title: pickertitle,
                showDistrict: !disableDistrict,
                value: text.val(),
                cssClass:"weui-citypicker",
                onChange: function (picker, values, displayValues) {
                    var p = 0;

                    $(that).find(".provincecode").val(values[0]);
                    $(that).find(".citycode").val(values[1]);

                    if (values.length == 3) {
                        $(that).find(".districtcode").val(values[2]);
                    }

                    //$(textbox).val(values[0] + ":" + values[1]);

                    //if (typeof onchangescript != "undefined") {
                    //    __callBackFuncOrStr(onchangescript, textbox);
                    //}
                },
                onOpen: function(picker) {
                    $(picker.container).parent().css("z-index", 9999);
                    isPickerOpened = true;
                },
                onClose: function() {
                    isPickerOpened = false;
                }
            });

            var value = text.val();

            if (value) {
                var raw = $.rawCitiesData;

                var values = value.split(" ");

                var province = firstOrDefault(raw,
                    function (index, value) {
                        return value.name === values[0];
                    },
                    null);

                if (province) {
                    var city = firstOrDefault(province.sub,
                        function (index, value) {
                            return value.name === values[1];
                        },
                        null);

                    if (city) {
                        $(that).find(".provincecode").val(province.code);
                        $(that).find(".citycode").val(city.code);

                        if (values.length == 3) {
                            var dis = firstOrDefault(city.sub,
                                function (index, value) {
                                    return value.name === values[2];
                                },
                                null);

                            $(that).find(".districtcode").val(dis.code);
                        }
                    }
                }

            }

        });
    }

    var tabbar=function(e){
        $(e).find(".weui-tab").each(function(){
            var tab=$(this);

            var barHeight=tab.find(".weui-tabbar").outerHeight();

            tab.find(".weui-tab__bd").css("padding-bottom", barHeight + "px");

            $(tab).find(".weui-tab__bd-item").each(function(){
                var holder=$(this).find(".holder");
                holder.height(barHeight);  
            })

            
        })
    }

    var panel=function(e){
        $(e).find(".weui-panel").each(function(){
            var panel=$(this);

            if($(panel).find(".pullToRefreshCollection").length>0){
                $(panel).addClass("with-pull-to-refresh");
                var panelBody=$(panel).find(".weui-pull-to-refresh");
                var panelHeader=$(panel).find(".weui-panel__hd");

                $(window).resize(function(){
                    var bodyHeidht=$(panel).outerHeight()-$(panelHeader).outerHeight();
                    panelBody.height(bodyHeidht);
                })

                var bodyHeidht=$(panel).outerHeight()-$(panelHeader).outerHeight();
                panelBody.height(bodyHeidht);
            }

           
        })
    }

    var formlinkfield = function(e) {
        $(e).find(".mobileui-form-field.weui-cells_link").each(function() {
            var gotoUrl = $(this).data("goto");
            var that = $(this);

            if (gotoUrl && gotoUrl != "") {
                $(this).click(function() {
                    WebUIJS.GoTo(gotoUrl, that);
                });
            }
        });
    }

    //数据选择器
    var datapicker = function (e) {
        e = $(e);

        if ($(e).is(".weui-popup_datapicker")) {
            e = $(e);
        } else {
            e = $(e).find(".weui-popup_datapicker");
        }

        $(e).each(function() {
            var that = $(this);

            $(that).find(":radio").change(function() {
                if ($(this).is(":checked")) {
                    $(that).find(".btn-select").click();
                }
            });

            $(that).find(".btn-select").click(function () {
                var values = [];

                $(that).find("input:checked").each(function () {
                    try {
                        var value = JSON.parse($(this).val());

                        values.push(value);
                    } catch (e1) {

                    }
                });

                if (values.length <= 0) {
                    WebUIJS.Toptip("选项不能为空", 1000, WebUIJS.Toptip.Style.Warning);
                } else {
                    $.closePopup();
                    $(that).data("onselectedcallback")(values);
                    $(that).remove();
                }
            });
        });
    }

    var modal = function (e) {
        if (e.is(".weui-dialog")) {
            e = $(e);
        } else {
            e = $(e).find(".weui-dialog");
        }

        //$(e).each(function () {
        //    var cmodal = $(this);

        //    if (cmodal.data("hideoncilckmask")=="True") {
        //        $(".weui-mask[for='" + cmodal.data("modalindex") +"']").click(function () {
        //            var mask = $(this);
        //            var forid = mask.attr("for");

        //            if (!isPickerOpened) {
        //                WebUIJS.CloseModalWindow(forid);
        //            }

                
        //        });                
        //    }


        //});
    }

    //var swipeout = function(e) {
    //    $()
    //}
    datapicker(collection);
    modal(collection);
    swiped(collection);
    pullToRefresh(collection);
    loadmore(collection);
    multiImageUploader(collection);
    singleImageUploader(collection);
    mobileVCode(collection);
    vcode(collection);
    warnTips(collection);
    datepicker(collection);
    dateptimeicker(collection);
    timerPicker(collection);
    counter(collection);
    slider(collection);
    querybox(collection);
    listbar(collection);
    listview(collection);
    
    tabbar(collection);
    panel(collection);
    formlinkfield(collection);


    try {
        FastClick.attach(collection);
    } catch (e) {

    }

}

WebUIJS.GetJson = function (url, data, onsuccess, onerror, oncompleted, onbeforceSend) {
    $.ajax(url, {
        async: true,
        cache: false,
        type: "GET",
        data: data,
        dataType: "json",
        beforeSend: function () {
            if (typeof (onbeforceSend) != "undefined" && onbeforceSend != null) {
                onbeforceSend();
            }
        },
        success: function (result, status, xhr) {
            if (typeof (onsuccess) != "undefined" && onsuccess != null) {
                onsuccess(result, status, xhr);
            }

        },
        error: function (xhr, status, error) {
            if (typeof (onerror) != "undefined" && onerror != null) {
                onerror(xhr, status, error);
            }
        },
        complete: function (xhr, status) {
            if (typeof (oncompleted) != "undefined" && oncompleted != null) {
                oncompleted(xhr, status);
            }
        }
    });
}

WebUIJS.Get = function (url, data, onsuccess, onerror, oncompleted, onbeforceSend) {
    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "GET",
        data: data,
        beforeSend: function () {
            if (typeof (onbeforceSend) != "undefined" && onbeforceSend != null) {
                onbeforceSend();
            }
        },
        success: function (result, status, xhr) {
            if (typeof (onsuccess) != "undefined" && onsuccess != null) {
                onsuccess(result, status, xhr);
            }

        },
        error: function (xhr, status, error) {
            if (typeof (onerror) != "undefined" && onerror != null) {
                onerror(xhr, status, error);
            }
        },
        complete: function (xhr, status) {
            if (typeof (oncompleted) != "undefined" && oncompleted != null) {
                oncompleted(xhr, status);
            }
        }
    });
}


WebUIJS.PostJson = function (url, data, onsuccess, onerror, oncompleted, onbeforceSend) {
    $.ajax(url, {
        async: true,
        cache: false,
        type: "POST",
        data: data,
        dataType: "json",
        beforeSend: function () {
            if (typeof (onbeforceSend) != "undefined" && onbeforceSend != null) {
                onbeforceSend();
            }
        },
        success: function (result, status, xhr) {
            if (typeof (onsuccess) != "undefined" && onsuccess != null) {
                onsuccess(result, status, xhr);
            }

        },
        error: function (xhr, status, error) {
            if (typeof (onerror) != "undefined" && onerror != null) {
                onerror(xhr, status, error);
            }
        },
        complete: function (xhr, status) {
            if (typeof (oncompleted) != "undefined" && oncompleted != null) {
                oncompleted(xhr, status);
            }
        }
    });

}


WebUIJS.Post = function (url, data, onsuccess, onerror, oncompleted, onbeforceSend) {

    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "POST",
        data: data,
        //dataType: "json html text",
        beforeSend: function () {
            if (typeof (onbeforceSend) != "undefined" && onbeforceSend != null) {
                onbeforceSend();
            }
        },
        success: function (result, status, xhr) {
            if (typeof (onsuccess) != "undefined" && onsuccess != null) {
                onsuccess(result, status, xhr);
            }

        },
        error: function (xhr, status, error) {
            if (typeof (onerror) != "undefined" && onerror != null) {
                onerror(xhr, status, error);
            }
        },
        complete: function (xhr, status) {
            if (typeof (oncompleted) != "undefined" && oncompleted != null) {
                oncompleted(xhr, status);
            }
        }
    });

}


function __callBackFuncOrStr(funcOrStr, sender, argslist) {
    if (funcOrStr == null) {
        return;
    }

    //if (!sender) {
    //    sender = this;
    //}

    if (typeof argslist == "undefined" || argslist == null) {
        argslist = [];
    }

    if(sender.length>0){
        sender=sender[0];
    }

    try {
        if (typeof funcOrStr == "string") {
            //arguments=argslist;
            new Function('e', funcOrStr).apply(sender,argslist);
        } else {
            funcOrStr.apply(sender, argslist);
        }
    } catch (e) {
        console.log(e.message);
        var p = 0;
    }

}

var __fileChangeHandler = function (fileElement, isAjax, ajaxUrl, ajaxProcessgram, onSuccessCallback, onFaildCallback,onBeforceUpload) {
    

    $(fileElement).change(function(){
        if(fileElement.files.length<=0){
            return false;
        }

        if (isAjax) {
            var formData=new FormData();
            formData.append($(fileElement).data("name"),fileElement.files[0]);
            //formData.append();

            $.ajax({
                url: ajaxUrl, //上传地址
                type: 'POST',
                cache: false,
                data: formData, //表单数据
                processData: false,
                contentType: false,
                xhr: xhrOnProgress(function (e) {
                    if (typeof ajaxProcessgram != "undefined" && ajaxProcessgram != null) {
                        ajaxProcessgram(((e.loaded / e.total) * 100));
                    }

                }),
                beforeSend:function(e){
                    if(onBeforceUpload){
                        onBeforceUpload();
                    }
                },
                success: function (data) {
                    if (typeof onSuccessCallback != "undefined" && onSuccessCallback != null) {
                        onSuccessCallback(data);
                    }
                    // if (data.IsSuccess) {
                        
                    // } else {
                    //     WebUIJS.Toptip("上传文件错误:" + data.Message);
                    //     if (typeof onFaildCallback != "undefined" && onFaildCallback != null) {
                    //         onFaildCallback(data);
                    //     }
                    // }
                },
                error: function (e) {
                   // WebUIJS.Toptip("上传文件错误:" + data.Message);
                    if (typeof onFaildCallback != "undefined" && onFaildCallback != null) {
                        onFaildCallback(new {
                            IsSuccess:false,
                            Message:"Http错误:"+e.message
                        });
                    }
                }
            });
        } else {
            try {
                var reader = new FileReader();
                reader.onload = function (evt) {
                    onSuccessCallback({
                        ReturnData: evt.target.result
                    });
                }
                reader.readAsDataURL(fileElement[0]);
            } catch (e) {

            }
        }
    })

    return fileElement;
}

var xhrOnProgress = function (fun) {
    xhrOnProgress.onprogress = fun; //绑定监听
    //使用闭包实现监听绑
    return function () {
        //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
        var xhr = $.ajaxSettings.xhr();
        //判断监听函数是否为函数
        if (typeof xhrOnProgress.onprogress !== 'function')
            return xhr;
        //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
        if (xhrOnProgress.onprogress && xhr.upload) {
            xhr.upload.onprogress = xhrOnProgress.onprogress;
        }
        return xhr;
    }
}


function __getFuncID(func) {
    var id = "callback_" + Date.parse(new Date());

    funcs[id] = func;

    return id;
}

function __callFuncByID(id, args) {
    funcs[id](args);
}

function __raiseEvent(eventName, args) {
    var array = eventHandlers[eventName];

    if (!array || array.length <= 0) {
        return;
    }

    for (var i = 0; i < array.length; i++) {
        array[i].call(window, args);
    }
}

var randomIndex = 0;

function __getRandomID() {
    randomIndex += 1;
    //var newRandom = randomIndex;
    return "randomID_" + randomIndex;
}

function __setRandomData(idOrValue, value) {
    if (typeof value == "undefined") {
        value = idOrValue;

        idOrValue = __getRandomID();
    }

    randomData[idOrValue.toString()] = value;

    return idOrValue;
}

//根据配置,使用get或post的方式,获取html数据,内部使用
function __httpGetOrPostDataByHtml(url, data, onsuccess, onError, httpMethod, isShowLoading) {
    if (typeof httpMethod == "undefined") {
        httpMethod = "get";
    }

    if (typeof isShowLoading == "undefined") {
        isShowLoading = true;
    }

    if (httpMethod == "get") {
        WebUIJS.Get(url,
            data,
            function (ret) {
                __callBackFuncOrStr(onsuccess, ret, [ret]);
            },
            null,
            function () {
                if (isShowLoading) WebUIJS.CloseLoading()
            },
            function () {
                if (isShowLoading) WebUIJS.Loading();
            });
    } else {
        WebUIJS.Post(url,
            data,
            function (ret) {
                __callBackFuncOrStr(onsuccess, ret, [ret]);
            },
            null,
            function () {
                if (isShowLoading) WebUIJS.CloseLoading()
            },
            function () {
                if (isShowLoading) WebUIJS.Loading();
            });
    }
}


function __getRandomDataByID(id) {
    return randomData[id.toString()];
}

function __triggerRadioGroupChange(radio) {
    var name = $(radio).attr("name");

    $(':radio[name="' + name + '"]').trigger("change");

}

function __switchElementChecked(el) {
    if ($(el).length > 0) {
        $(el).each(function () {
            if ($(this).is(":checked")) {
                $(this).prop("checked", null);
            } else {
                $(this).prop("checked", "checked");
            }

            if ($(this).is(":radio")) {
                var name = $(this).attr("name");

                $(':radio[name="' + name + '"]').trigger("change");
            } else {
                $(this).trigger("change");
            }
        })
    }


}

function __updateModalByUrl(modal, newDom) {
    var item = $(modal);

    if (!$(modal).is(".weui-dialog")) {
        item = $(modal).closest(".weui-dialog");
    }

    var newItem = $(item).empty().replaceWith(newDom);

    WebUIJS.RefreshEvent(newItem);
}

function __formSubmit(form, onSuccessCallback, extdata) {

    var that = $(form);

    var method = $(that).attr("method");
    var action = $(that).attr("action");
    var isAjax = $(that).data("ajax");
    var updateEl = $(that).data("updateelemid");

    if (isEmpty(method)) {
        method = "get";
    }

    method = method.toLowerCase();

    if (isEmpty(action)) {
        action = window.location.href;
    }

    if (isEmpty(isAjax)) {
        isAjax = "True";
    }

    if (isEmpty(updateEl)) {
        updateEl = "html";
    } else {
        updateEl = "#" + updateEl;
    }


    if (isAjax) {
        var data = $(that).serialize();

        if (extdata) {
            if (data.length > 0) {
                
                data += "&";
            }

            for (var i in extdata) {
                if (extdata.hasOwnProperty(i)) {
                    data += (i + '=' + extdata[i] + '&');
                }
            }

            data = data.slice(0, data.length - 1);
        }

        if (action.indexOf("modalindex") > 0) {
            action = action.replace(/modalindex=randomID_(\w*)(&*)/g, '');
            action = action.replace("&&", '&');
        }

        if (method == "get") {
            WebUIJS.Get(action,
                data,
                function (data) {
                    var newItem = $(data);

                    var modalIndex = $(updateEl).data("modalindex");
                    var onclose = $(updateEl).data("onclose");

                    $(updateEl).replaceWith(newItem[0]);

                    $(updateEl).data("modalindex", modalIndex).data("onclose", onclose);
                    $(updateEl).addClass(modalIndex).addClass("weui-dialog--visible");


                    WebUIJS.RefreshEvent(newItem);

                    if (onSuccessCallback != undefined && onSuccessCallback != null) {
                        onSuccessCallback(newItem);
                    }
                },
                null,
                function () {
                    WebUIJS.CloseLoading();
                },
                function () {
                    WebUIJS.Loading();
                });
        } else {
            WebUIJS.Post(action,
                data,
                function (data) {
                    var newItem = $(data);

                    var modalIndex = $(updateEl).data("modalindex");
                    var onclose = $(updateEl).data("onclose");

                    $(updateEl).replaceWith(newItem[0]);

                    $(updateEl).data("modalindex", modalIndex).data("onclose", onclose);
                    $(updateEl).addClass(modalIndex).addClass("weui-dialog--visible");

                    WebUIJS.RefreshEvent(newItem);

                    if (onSuccessCallback != undefined && onSuccessCallback != null) {
                        onSuccessCallback(newItem);
                    }
                },
                null,
                function () {
                    WebUIJS.CloseLoading();
                },
                function () {
                    WebUIJS.Loading();
                });
        }
    } else {
        WebUIJS.Loading();
        $(form).submit();
    }
}

function __divFormSubmit(div, onsuccess, extdata) {
    var that = $(div);

    var method = $(that).attr("method");
    var action = $(that).attr("action");
    var updateEl = $(that).data("updateelemid");

    if (isEmpty(method)) {
        method = "get";
    }

    if (isEmpty(action)) {
        action = window.location.href;
    }

    if (isEmpty(updateEl)) {
        updateEl = "html";
    } else {
        updateEl = "#" + updateEl;
    }


    var data = $(this).find("input,textarea,select").serialize();

    if (extdata) {
        data = $.extend(data, extdata);
    }

    if (method == "get") {
        WebUIJS.Get(action,
            data,
            function (data) {
                var newItem = $(data);

                var modalIndex = $(updateEl).data("modalindex");
                var onclose = $(updateEl).data("onclose");

                $(updateEl).replaceWith(newItem[0]);

                $(updateEl).data("modalindex", modalIndex).data("onclose", onclose);
                $(updateEl).addClass(modalIndex).addClass("weui-dialog--visible");

                WebUIJS.RefreshEvent(newItem);

                if (onSuccessCallback != undefined && onSuccessCallback != null) {
                    onSuccessCallback(newItem);
                }
            },
            null,
            function () {
                WebUIJS.CloseLoading();
            },
            function () {
                WebUIJS.Loading();
            });
    } else {
        WebUIJS.Post(action,
            data,
            function (data) {
                var newItem = $(data);

                var modalIndex = $(updateEl).data("modalindex");
                var onclose = $(updateEl).data("onclose");

                $(updateEl).replaceWith(newItem[0]);

                $(updateEl).data("modalindex", modalIndex).data("onclose", onclose);
                $(updateEl).addClass(modalIndex).addClass("weui-dialog--visible");

                WebUIJS.RefreshEvent(newItem);

                if (onSuccessCallback != undefined && onSuccessCallback != null) {
                    onSuccessCallback(newItem);
                }
            },
            null,
            function () {
                WebUIJS.CloseLoading();
            },
            function () {
                WebUIJS.Loading();
            });
    }
}

function __showModal(el, onOpen, onclose, notAppendTobody) {
    var mask = $("<div class='weui-mask'></div>").appendTo(document.body);
    mask.show();

    var dialog;

    if (notAppendTobody) {
        dialog = $(el[0]);
    } else {
        dialog = $(el[0]).appendTo(document.body);
    }
    
    var modalID = __getRandomID();

    //
    mask.addClass("weui-mask--visible");
    $(mask).attr("for", modalID);

    if (!dialog.is(".weui-dialog--visible")) {
        dialog.addClass("weui-dialog--visible");
    }


    $(dialog).data("modalindex", modalID);

    $(dialog).addClass(modalID);

    var hideOnClickMask = $(dialog).data("hideoncilckmask");

    if (hideOnClickMask == "True") {
        $(mask).click(function () {
            if (!isPickerOpened) {
                __closeModal(modalID);
            }

            //__closeModal(modalID);
        });
    }

    if ($(dialog).height() / $(window).height() > 0.8) {
        var maxheight = $(dialog).height();

        if (maxheight > $(window).height()) {
            maxheight = $(window).height();
        }

        var bd = $(dialog).find(".weui-dialog__bd");
        bd.css("max-height", (maxheight * 0.665) + "px");
        //$(dialog).css("top", "49%");
    }

    var modalRight = $(dialog).offset().left + $(dialog).width() - 16;

    var floatClose = $("<a class=\"weui-dialog_floatclose\"></a>");
    $(floatClose).attr("for", modalID);

    $(mask).parent().append(floatClose);

    $(dialog).find(".weui-dialog__Close").click(function() {
        if (!isPickerOpened) {
            __closeModal(modalID);
        }
    });

    floatClose.click(function() {
        if (!isPickerOpened) {
            __closeModal(modalID);
        }
    });

    $(dialog).data("onclose", function (e) {
        $(floatClose).remove();
        $('body').css("overflow", "auto");
        if (onclose) {
            //$('body').css("overflow", "auto");
            onclose(e);
        }
    });

    //if (onclose) {
    //    $(dialog).data("onclose", onclose);
    //}
    dialog.show();

    floatClose.css("left", modalRight + "px");
    floatClose.css("top", ($(dialog).offset().top - 16) + "px");
    floatClose.css("z-index", parseInt($(dialog).css("z-index")) + 1);

    if (onOpen) {
        onOpen(dialog);
        //__callBackFuncOrStr(onOpen, dialog, [dialog]);
    }

    $('body').css("overflow", "hidden");

    //$(".weui-mask--visible").removeClass("weui-mask--visible").transitionEnd(function () {
    //    $(this).remove();
    //});
    //$(".weui-dialog--visible").removeClass("weui-dialog--visible").transitionEnd(function () {
    //    $(this).remove();
    //});
}

function __closeModal(index, triggerClose) {

    if (typeof index != "string") {
        index = $(index).closest(".weui-dialog").data("modalindex");
    }

    var onclose = $(".weui-dialog." + index).data("onclose");

    $(".weui-mask--visible[for=\"" + index + "\"]").remove();

    $(".weui-dialog_floatclose[for=" + index + "]").remove();



    $(".weui-dialog." + index).remove();
    

    if (onclose && (triggerClose != false)) {
        __callBackFuncOrStr(onclose, this, [this]);
    }

    if ($(".weui-dialog").length<=0) {
        $('body').css("overflow", "auto");
    }
    
    

    //$(".weui-dialog[data-modalindex=\"" + index + "\"]").transitionEnd(function () {
    //    var onclose = $(this).data("onclose");

    //    if (onclose) {
    //        __callBackFuncOrStr(onclose, this, [this]);
    //    }

    //    $(this).remove();
    //}).removeClass("weui-dialog--visible");
}

//弹出一个消息页
function __showMsgPage(el, onsuccess, onclose) {
    var el = $(el);

    var pageID = __getRandomID();

    el.data("pageid", pageID);

    if (onclose) {
        el.data("onclose", onclose);
    }

    //添加popup元素

    var popup = $("<div id=\"" + pageID + "\" class='weui-popup__container'><div class=\"weui-popup__modal\"></div></div>")

    popup.appendTo(document.body)

    var modal = $(popup).find(".weui-popup__modal");

    modal.append(el);

    modal.on("open", function () {
        __callBackFuncOrStr(onsuccess, el, [el]);
    })

    modal.on("close", function () {
        __callBackFuncOrStr(onclose, el, [el]);
    })

    $(popup).popup();
}

function __closeMsgPage(id){

    if(id){
        var container=$("#" + id);
        
        var autoRemove=container.data("autoremove");

        $.closePopup($(container),autoRemove);
    }
    else{
        $.closePopup();
    }

    
}